package org.microdream.easy.deploy.service;

import ice.server.comm.BaseServiceImpl;
import ice.server.comm.CommRepository;
import org.microdream.easy.deploy.dao.DSequenceRepository;
import org.microdream.easy.deploy.po.DSequence;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DSequenceService extends BaseServiceImpl<DSequence, Integer>{

    @Resource
    private DSequenceRepository dSequenceRepository;

    @Override
    public CommRepository<DSequence, Integer> getRepository() {

        return dSequenceRepository;
    }

    @Override
    public Integer getIdenty(DSequence t) {
        return t.getId();
    }

    public String getNextSequence(String name, String a) {
        //格式化数值位数
        DecimalFormat decimalFormat=new DecimalFormat(a);
        //根据事业部简称取序列当前值
        Map map = new HashMap();
        map.put("seqName",name);
        List<DSequence> sysSequences = this.find(map);

        DSequence dSequence = null;
        if(CollectionUtils.isEmpty(sysSequences)){
            dSequence = this.createSysSequence(name, 2);
        } else {
            dSequence = sysSequences.get(0);
        }

        dSequence.setCurrentVal(dSequence.getIncrementVal()+dSequence.getCurrentVal());
        this.save(dSequence);
        return dSequence.getSeqName() + decimalFormat.format(dSequence.getCurrentVal());
    }

    private DSequence createSysSequence(String name, int size) {
        DSequence sys = new DSequence();
        sys.setSeqName(name);
        sys.setCurrentVal(size);
        sys.setIncrementVal(1);
        sys.setUpdateDate(new Date(System.currentTimeMillis()));
        super.save(sys);

        return sys;
    }
}
